package epam.marchenko.library.services;

import java.util.List;

import javax.persistence.NoResultException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import epam.marchenko.library.controller.AdminController;
import epam.marchenko.library.domain.OutcomeRecord;
import epam.marchenko.library.domain.User;
import epam.marchenko.library.repository.OutcomeRecordRepository;
import epam.marchenko.library.repository.UserRepository;

@Service
public class UserServiceImpl implements UserService {

	private static final Logger logger = LoggerFactory
			.getLogger(AdminController.class);

	@Autowired
	UserRepository userRep;
	@Autowired
	OutcomeRecordRepository outcomeRep;
	@Autowired
	OutcomeRecordService outcomeService;

	public void addUser(User user) {
		userRep.create(user);
	}

	@Override
	public User findUserByLogin(String login) {
		return userRep.findByLogin(login);
	}

	@Override
	public boolean isAvailableLogin(String login) {
		try {
			userRep.findByLogin(login);
		} catch (NoResultException e) {
			return true;
		}
		return false;
	}

	private boolean userExist(User user) {
		return userRep.find(user) != null;
	}

	@Override
	public boolean userCanGetBook(User user) {
		if (!userExist(user)) {
			logger.info("User doesn't exist");
			return false;
		}
		List<OutcomeRecord> lorders = outcomeService
				.getActiveOrdersForUser(user);
		logger.info("List size: " + lorders.size());
		return lorders.size() < 3;
	}

	@Override
	public List<User> findAllUsers() {
		return userRep.findAll();
	}

	@Override
	public User findUserById(int id) {
		return userRep.findById(id);
	}

	@Override
	public List<User> searchUser(String searchedName) {
		return userRep.searchByName(searchedName);
	}

	@Override
	public List<User> findPart(int pageNum, int perPage) {
		return userRep.findPart(pageNum, perPage);
	}

	@Override
	public Long recordCount() {
		return userRep.countUsers();
	}

}
